<template>
	<view class="content">
		<Tab :labelList="labelList || []" :activeIndex="activeIndex || 0" @changeIndex="changeActive"
			@addCate="addCate"></Tab>
		<MainList :labelList="labelList || []" :activeIndex="activeIndex || 0" @changeIndex="changeActive"></MainList>
		<view class="empty-tip" style="font-size: 40rpx; text-align: center; padding: 20rpx;"
			v-if="labelList && labelList.length === 0">
			请先加入一个药品分类↑
		</view>
		<view class="cateDialog" v-if="cateDialog">
			<h2>添加分类</h2>
			<input type="text" v-model="addCateName" placeholder="请输入要加入的分类名称" />
			<view style="display: flex;">
				<view class="btn" style="background-color: #ccc;" @click="cateDialog = false">取消</view>
				<view class="btn" @click="confirmAddCate">确定</view>
			</view>
		</view>
	</view>
</template>


<script setup>
	import {
		ref,
		onBeforeMount,
		onMounted,
		computed
	} from 'vue';
	import { useUserStore } from '../../store/User';
	import { onShow } from '@dcloudio/uni-app';

	const userStore = useUserStore();
	const activeIndex = ref(0);
	const labelList = ref([]);
	const cateDialog = ref(false);
	const addCateName = ref('');

	// 使用计算属性获取用户信息
	const userInfo = computed(() => {
		const info = uni.getStorageSync('userInfo');
		return info || {};
	});

	const fetchData = async () => {
		try {
			uni.showLoading({ title: '加载中' });
			const {
				familyId,
				username
			} = userInfo.value;

			if (!familyId) {
				uni.navigateTo({ url: '/pages/login/login' });
				return;
			}

			const res = await uniCloud.callFunction({
				name: 'getFamily',
				data: {
					familyId,
					username
				}
			});

			if (res.result && res.result.data && res.result.data[0]) {
				const arr = res.result.data[0].cateList || [];
				uni.setStorageSync('cate', arr);
				labelList.value = arr || []; // 确保是数组

				const familyName = res.result.data[0].name;
				const members = res.result.data[0].members || [];

				userStore.setFamilyName(familyName);
				userStore.setMembers(members);
			}
		} catch (err) {
			console.error('fetchData error:', err);
			labelList.value = []; // 出错时设置为空数组
		} finally {
			uni.hideLoading();
		}
	};

	// 确保在页面加载前初始化数据
	onBeforeMount(async () => {
		userStore.initState(); // 初始化 store 状态
		await fetchData();
	});

	onMounted(() => {
		// 先保证token存在
		if (!uni.getStorageSync('token')) {
			uni.navigateTo({ url: '/pages/login/login' });
			return;
		}

		// 注册页面显示事件
		onShow(async () => {
			if (userStore.flashFlag) {
				userStore.setFlashFlag(false);
				await fetchData();
			}
		});
	});

	const changeActive = index => {
		activeIndex.value = index;
	};

	const addCate = () => {
		cateDialog.value = true;
	};
	const confirmAddCate = () => {
		// 表单验证
		if (!addCateName.value) {
			uni.showToast({
				title: '请输入要添加的分类名称',
				icon: 'none'
			});
			return;
		}
		// 拿到家庭id
		const { familyId } = uni.getStorageSync('userInfo');
		// 调用云函数添加分类
		uniCloud.callFunction({
			name: 'addCate',
			data: {
				familyId,
				cateName: addCateName.value
			},
			success: res => {
				uni.showToast({
					title: res.result.msg,
					icon: 'none'
				});
				// 关闭弹窗
				cateDialog.value = false;
				// 清空输入框
				addCateName.value = '';
				// 重新获取分类
				fetchData();
			},
			fail: err => {
				console.log(err);
			},
		});
	};
</script>

<style scoped lang="scss">
	@import "../../uni.scss";

	.cateDialog {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 90%;
		height: 70vh;
		background-color: #fff;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		box-sizing: border-box;



		input {
			width: 80%;
			height: 40px;
			border: 1px solid #ccc;
			border-radius: 5px;
			padding: 0 10px;
			margin: 20px 0;
		}

		.btn {
			width: 100px;
			height: 40px;
			line-height: 40px;
			text-align: center;
			background-color: #007aff;
			color: #fff;
			border-radius: 5px;
			margin: 0 10px;
		}
	}

	.empty-tip {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		background-color: rgba(255, 255, 255, 0.9);
		padding: 20rpx 40rpx;
		border-radius: 10rpx;
		box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);
	}
</style>